package com.zhiyou100.crm.servlet.department;

import java.io.IOException;
import java.sql.Date;
import java.sql.Timestamp;
import java.text.SimpleDateFormat;
import java.time.LocalDateTime;
import java.util.List;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import com.zhiyou100.crm.pojo.AdminBaseServlet;
import com.zhiyou100.crm.pojo.Department;
import com.zhiyou100.crm.service.DepartmentService;
import com.zhiyou100.crm.service.impl.DepartmentServiceImpl;

/**
 * 更新部门
 */
@WebServlet("/department/update")
public class UpdateServlet extends AdminBaseServlet {
	private static final long serialVersionUID = 1L;
	DepartmentService departmentService=new DepartmentServiceImpl();


	@Override
	protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		request.setCharacterEncoding("utf-8");
		response.setCharacterEncoding("utf-8");
		response.setContentType("text/html; charset=UTF-8");
		String id=request.getParameter("id");
		int departmentId = Integer.parseInt(id);
		request.getSession().setAttribute("id",id);
		List<Department> departments = departmentService.queryAll();
		Department department=new Department();
		for (int i = 0; i <departments.size(); i++) {
			int department_id = departments.get(i).getDepartment_id();
			if(departmentId==department_id){
				department=departments.get(i);
				request.setAttribute("department",department);
				break;
			}
		}
		if(department!=null) {
			request.getRequestDispatcher("/WEB-INF/view/department/update.jsp").forward(request, response);
		}else{
			response.sendRedirect(request.getContextPath()+"/list.jsp");
		}


	}

	@Override
	protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		request.setCharacterEncoding("utf-8");
		response.setCharacterEncoding("utf-8");
		response.setContentType("text/html; charset=UTF-8");
		Object departmentId = request.getSession().getAttribute("id");
		int departmentId1=Integer.parseInt((String)departmentId);
		String departmentName=request.getParameter("departmentName");
		String departmentDesc = request.getParameter("departmentDesc");
		SimpleDateFormat df = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
		long l = System.currentTimeMillis();
		String format = df.format(new Date(l));
		Timestamp time=Timestamp.valueOf(format);
		Department department=new Department(departmentId1,departmentName,departmentDesc,time);
		int a=departmentService.updateDepartment(department);
		if(a>0) {
			System.out.println("成功");
			response.sendRedirect(request.getContextPath()+"/department/list");
		}else{
			System.out.println("失败");
			response.sendRedirect(request.getContextPath()+"/WEB-INF/view/department/update.jsp");
		}

	}

}
